package com.practice.security.filter;

import com.practice.exception.TokenException;
import com.practice.jwt.JwtUtils;
import com.practice.system.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CheckTokenFilter extends OncePerRequestFilter {

    //登录路径
    private final String signUrl = "/user/sign";
    private final String loginUrl = "/user/login";
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    UserMapper userMapper;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
//        获取请求路径
        String requestURI = request.getRequestURI();
        if (requestURI.equals(signUrl) || requestURI.equals(loginUrl)) {
            filterChain.doFilter(request, response);
            return;
        }
        String token = request.getHeader("token");

        String accountName;
        try {
            //解析token
            accountName = jwtUtils.getAccountNameFromToken(token);
        } catch (Exception e) {
            throw new TokenException("token非法,再搞请你吃一辈子饭！");
        }
        UserDetails user = userMapper.getUser(accountName);
        if (user == null) {
            throw new TokenException("token验证失败！");
        }
        //1.包装用户信息
        //TODO 权限设置
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user, null, null);
        //存储用户信息到SecurityContextHolder
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request, response);
    }
}
